from flask import Flask,jsonify,render_template,request,escape,session, redirect, url_for
import pandas as pd
import urllib
import json
import requests
import base64
import generateCi
from panduan import panduan_login
from pymysql import connect
from weatherapi import weather


def look_over():
    con = connect(host="127.0.0.1",port=3306,user="root",password="123456789",db="user")
    cursor1 = con.cursor()
    sql = "select * from student"
    cursor1.execute(sql)
    res = cursor1.fetchall()
    print(res)
    return res

app = Flask(__name__)


#日志
def log_request(req:"flask request",res:str):
  with open("vsearch.log","a") as log:
    print(req.form,req.host_url,req.remote_addr,file=log,sep="|")


# 注册添加账号
@app.route('/register', methods=['GET','POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
    else:
        return render_template('register.html')
# 登陆
@app.route('/login',methods=['POST'])
def login() -> 'html':
    return render_template('login.html',the_title ="注册")


#选择功能服务
@app.route('/index',methods=['POST'])
def index() -> 'html':
    zhanghao = request.form.get("zhanghao") 
    mima = request.form.get("mima")
    a = panduan_login(zhanghao, mima)
    if a == "true":
        return render_template('gongneng.html')
    else:
        return "登录失败"

# 输入百度API的ID和秘钥
client_id ='2O2Oj8FVRK1riQOsg2KdccbX'
client_secret ='EPxAxx7FETotdOU7gPZOo53sabILiXLI'

# 百度文本纠错API使用的access_token
def get_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
    request = urllib.request.Request(host)
    request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = urllib.request.urlopen(request)
    token_content = response.read()
    if token_content:
        token_info = json.loads(token_content)
        token_key = token_info['access_token']
    return token_key

# 调用百度API的文本纠错
def txt_correction(content):
    print ('原文：',content)
    token=get_token()
    url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/ecnet'
    params = dict()
    params['text'] = content
    params = json.dumps(params).encode('utf-8')
    access_token = token
    url = url + "?access_token=" + access_token
    request = urllib.request.Request(url=url, data=params)
    request.add_header('Content-Type', 'application/json')
    response = urllib.request.urlopen(request)
    content = response.read()
    if content:
        content=content.decode('GB2312')
        data = json.loads(content)
        item=data['item']
        print('纠错后：',item['correct_query'])


#登陆后的主页，有功能介绍
@app.route('/')
def index():
   return render_template('index.html')

# 文本纠错前
@app.route('/wenben',methods=['GET'])
def wen_ben():
    return render_template("wenbenjiucuo.html")
# 文本纠错后
@app.route("/txt_correction",methods=['POST'])
def txt_correction():
    token = get_token()
    content= request.form.get("txtcorr")
    print(content)
    res=txt_correct(content)
    return render_template("wenbenjiucuo.html",word=res[0])
# 宋词生成前
@app.route('/song_ci')
def song_ci():
    return render_template('generateCi.html', recommend=generateCi.random_name(), ci_name="")
# 宋词生成后
@app.route('/song_ci', methods=['POST'])
def generate():
    ci_content = generateCi.generate_ci(request.form['ci_name'])
    return render_template('generateCi.html', recommend=generateCi.random_name(), ci_content=ci_content)
# 调用高德API获取广州实时天气
@app.route("/we")
def we():
    key='074c0cf252bce9288b8a774fb78814e7'
    city='440100'
    extensions='base'
    a=weather(key,city,extensions)
    b=a['lives'][0]['city']
    c=a['lives'][0]['weather']
    d=a['lives'][0]['temperature']
    e=a['lives'][0]['windpower']
    f=a['lives'][0]['humidity']
    return render_template('tianqi.html',city=str(b),weather=str(c),temperature=str(d),windpower=str(e),humidity=str(f))

#调用日志
@app.route("/viewlog")
def view_log():
  contents=[]
  with open("vsearch.log","r") as log:
    for line in log:
      contents.append([])
      for item in line.split("|"):
        contents[-1].append(escape(item))
    titles= ["Formdata","Host_url","Remote_addr"]
  return render_template('view.html',the_data=contents,the_titles=titles)
if __name__=='__main__':
    app.run(debug=True)